/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.core.tapestry.base;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.internal.InternalConstants;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.Environment;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.libermundi.theorcs.core.tapestry.BasePage;
import org.libermundi.theorcs.core.tapestry.services.PageRenderSupport;

public abstract class BasePageImpl implements BasePage {
	@Inject
	private Messages _messages;
	
	@Inject
	private JavaScriptSupport _jsSupport;
	
	@Inject
	@Symbol("tapestry.production-mode")
	private boolean _productionMode;
	
	@Inject
	@Path("${core.scripts}/jquery.debug.js")
	private Asset _jsDump;
	
	@Inject
	private Environment _environment;
	
	@SetupRender
	public void initJSAndPageRenderSupport(){
		if(!_productionMode) {
			_jsSupport.importStack(InternalConstants.CORE_STACK_NAME);
			_jsSupport.importJavaScriptLibrary(_jsDump);
		}
		
		PageRenderSupport prs = new PageRenderSupport();
			prs.setPageTitle(getMessage(getPageId() + ".title"));
			prs.setPageDescription(getMessage(getPageId() + ".description"));
			prs.setPageKeywords(getMessage(getPageId() + ".keywords"));
			
		_environment.push(PageRenderSupport.class, prs);
	}
	
	@AfterRender
	public void cleanPageRenderSupport(){
		 _environment.pop(PageRenderSupport.class);
	}
	
	private String getMessage(String key, Object...args){
		String msg = _messages.format(key, args); 
		if(msg.startsWith("[[missing key:")){
			return "";
		}
		return msg;
	}	
	
}
